package com.zlz.ddns.seddns.remote.impl;

import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.dnspod.v20210323.DnspodClient;
import com.tencentcloudapi.dnspod.v20210323.models.*;
import com.zlz.ddns.seddns.domain.DDnsUpdateRecord;
import com.zlz.ddns.seddns.remote.TencentCloudDNSPodRemoteService;
import org.springframework.stereotype.Service;

/**
 * @Author: zhulinzhong
 * @Date: 2024/7/15
 */

@Service
public class TencentCloudDNSPodRemoteServiceImpl implements TencentCloudDNSPodRemoteService {

    private final DnspodClient dnspodClient;

    public TencentCloudDNSPodRemoteServiceImpl(DnspodClient dnspodClient) {
        this.dnspodClient = dnspodClient;
    }

    @Override
    public boolean add(DDnsUpdateRecord record) throws TencentCloudSDKException {
        CreateRecordRequest request = new CreateRecordRequest();
        request.setDomain("zlzblog.com");
        request.setSubDomain("ss");
        request.setRecordType("A");
        request.setRecordLine("默认");
        request.setValue(record.getTargetIp());
        CreateRecordResponse createRecordResponse = dnspodClient.CreateRecord(request);
        return true;
    }

    @Override
    public boolean update(DDnsUpdateRecord record) throws TencentCloudSDKException {
        RecordListItem item = this.query();
        if(item == null){
            return this.add(record);
        }
        ModifyRecordRequest request = new ModifyRecordRequest();
        request.setDomain("zlzblog.com");
        request.setSubDomain("ss");
        request.setRecordType(item.getType());
        request.setRecordLine(item.getLine());
        request.setValue(record.getTargetIp());
        request.setRecordId(item.getRecordId());
        request.setRecordLineId(item.getLineId());
        ModifyRecordResponse modifyRecordResponse = dnspodClient.ModifyRecord(request);
        return true;
    }

    @Override
    public boolean delete(DDnsUpdateRecord record) {
        return false;
    }

    @Override
    public RecordListItem query() throws TencentCloudSDKException {
        DescribeRecordListRequest request = new DescribeRecordListRequest();
        request.setDomain("zlzblog.com");
        request.setSubdomain("ss");
        DescribeRecordListResponse describeRecordListResponse = dnspodClient.DescribeRecordList(request);
        return describeRecordListResponse.getRecordList()[0];
    }
}

